<?php

class Cache_Redis extends Cache {

    protected $instant;

    public static function checkDriver() {
        return defined('Redis::REDIS_NOT_FOUND');
    }

    function __construct() {
        if (!self::checkDriver()) {
            throw new Exception("Can't use this driver for your system!");
        }
        try {
            $conf = explode(':', self::$options['redis']['server']);
            Yaf_Registry::set('redis', new Redis());
            $this->instant = Yaf_Registry::get('redis');
            $this->instant->connect($conf[0], $conf[1], self::$options['redis']['timeout']);
            $this->instant->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);
            $this->instant->setOption(Redis::OPT_PREFIX, self::$options['prefix']);
        } catch (RedisException $e) {
            throw new Exception($e->getMessage());
        }
    }

    protected function _set($key, $value = "", $tts = 300) {
        $tts = $tts ? $tts : NULL;
        return $this->instant->set($key, $value, $tts);
    }

    protected function _get($key) {
        $x = $this->instant->get($key);
        if ($x == false) {
            return null;
        } else {
            return $x;
        }
    }

    protected function _delete($key) {
        $this->instant->delete($key);
    }

    protected function _exist($key) {
        return $this->instant->exists($key);
    }

    protected function _clean() {
        $this->instant->flushAll();
    }

    protected function _stats() {
        $res = array(
            "info" => "",
            "size" => "",
            "data" => $this->instant->info(),
        );
        return $res;
    }

}
